package com.jietuo.class02;

/**
 * @author zhangx & jietuo_zx@163.com
 * @version 1.0
 * @date 2024/3/1
 * @description: 2，把给定的值都删除
 */
public class Code02_DeleteNode {

    public static void main(String[] args) {
        // node01 --> node02 --> node03 --> node01
        Node node01 = new Node(1);
        Node node02 = new Node(2);
        Node node03 = new Node(2);
        Node node04 = new Node(5);
        Node node05 = new Node(1);
        Node node06 = new Node(1);
        Node node07 = new Node(3);
        node01.next = node02;
        node02.next = node03;
        node03.next = node04;
        node04.next = node05;
        node05.next = node06;
        node06.next = node07;
        Node.printNode(node01);
        Node node = deleteNode(node01, 1);
        System.out.println("=====");
        Node.printNode(node);
    }

    public static Node deleteNode(Node head, int deleteValue) {
        while (head != null) {
            if (head.value != deleteValue) {
                break;
            }
            head = head.next;
        }
        // head 来到第一个不需要删除的位置
        Node pre = head;
        Node cur = head;
        while (cur != null) {
            if (cur.value == deleteValue) {
                pre.next = cur.next;
            } else {
                pre = cur;
            }
            cur = cur.next;
        }
        return head;
    }
}
